package com.yuanyu.server.impl;

import com.yuanyu.common.util.AssertUtil;
import com.yuanyu.common.util.PasswordUtil;
import com.yuanyu.mapper.mysqlMapper.AdminMapper;
import com.yuanyu.model.entity.Admin;
import com.yuanyu.model.vo.LoginVO;
import com.yuanyu.model.vo.PasswordVO;
import com.yuanyu.server.ILoginServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class LoginServerImpl implements ILoginServer {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public String updatePassword(String username, PasswordVO passwordVO) {
        AssertUtil.notTrue(passwordVO.getNewPasswords().equals(passwordVO.getOldPasswords()),"新旧密码相同");
        Admin admin = adminMapper.selAdminByUsername(username);
        AssertUtil.notNull(admin, "用户不存在");
        String password = PasswordUtil.MD5Cipher(passwordVO.getOldPasswords());
        AssertUtil.isTrue(password.equals(admin.getPassword()), "旧密码错误");
        AssertUtil.RegularExpression("^[a-zA-Z0-9]{4,12}$",passwordVO.getNewPasswords(),"密码只能由4至12位英文字母和数字组成");
        String newPassword = PasswordUtil.MD5Cipher(passwordVO.getNewPasswords());
        admin.setPassword(newPassword);
        int i = adminMapper.UpdateAdminByUsername(admin);
        AssertUtil.isTrue(i == 1, "修改失败");
        return "修改成功";
    }

    @Override
    public boolean login(LoginVO loginVO) {
        Admin admin = adminMapper.selAdminByUsername(loginVO.getUsername());
        AssertUtil.notNull(admin, "用户不存在");
        String password = PasswordUtil.MD5Cipher( loginVO.getPassword());
        AssertUtil.isTrue(password.equals(admin.getPassword()), "密码错误");
        return false;
    }
}
